from django.shortcuts import render, redirect

# Create your views here.

from django.http import HttpResponse,JsonResponse
import json
from django.shortcuts import render
from django.views.generic import View


class viewtemplatesss(View):
    def get(self,request):
        context = {'city':'北京','adict':{'name':'jjj','acc':'lll'},
                   'alist':[1,2,3,4]}
        return render(request,'index.html',context)






def session_demo(request):
    # 将缓存数据写入到session
    request.session['name'] = 'zxx'
#     读取缓存的session数据
    name = request.session.get('name')
    print(name)
    return HttpResponse('ok')








def weather1(request,city,year):
    """
    读取正则中的组提取的参数,读取路径的参数
    :param request:
    :param city:
    :param year:
    :return:
    """
    print('city=%s'%city)
    print('year=%s'%year)

    return HttpResponse('ok')

# 定义关键字（起别名）获取路径的参数，不需要遵守顺序传递
def weather2(request,city,year):
    print('city=%s'%city)
    print('year=%s'%year)

    return HttpResponse('kkk')
# 获取查询的字符串,处理同一个键带有多个值的情况
def weather3(request,city,year):
    print('city=%s'%city)
    print('year=%s'%year)

    a = request.GET.get('a')#成为第三个的a的值是因为通过get()取值会进行覆盖
    b = request.GET.get('b')
    a_list = request.GET.getlist('a')
    print(a,b,a_list)

    return HttpResponse('ooo')

# 演示请求体中读取表单数据
def get_body_from(request):
    a = request.POST.get('a')
    like = request.POST.get('like')
    a_list = request.POST.getlist('a')
    print(a,like,a_list)
    return HttpResponse('ok')
# 演示请求体中读取非表单数据
def get_body_json(request):
    """演示获取请求体中的非表单数据"""
    # 获取传输的二进制数据
    json_str = request.body
    # 把二进制数据转成字符串
    json_str = json_str.decode()
    # 把字符串转成字典,方便后续的取值
    req_data = json.loads(json_str)
    print(req_data['a'])
    print(req_data['b'])
    return HttpResponse('ok')

# 演示httpresponse响应头，状态码
def move(request):
    response = HttpResponse('itcast python')
    response.status_code = 400
    response['Itcast'] = 'python'
    return response

# 返回json数据,使用JsonResponse,可以帮助我们将数据转成json字符串，
# 帮设置响应头content-type为application/json
def demo(request):

    return JsonResponse({'city':'beijing','subject':'python'})

# redirect设置重定向
def view(request):

    return redirect('/demo')

# 设置cookie，通过HttpResponse对象中的set_cookie方法来获取
def cookie(request):
    response = HttpResponse('ok')
    response.set_cookie('itcast1','python1')
    response.set_cookie('itcast2','python2',max_age=300)
    return response

# 获取设置好的cookie,COOKIES,读取本次请求的cookie
def cookies(request):
    cookie1 = request.COOKIES.get('itcast1')
    print(cookie1)
    return HttpResponse('ok')